import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
import store from '@/store'
import { routes, asyncRoutes, initRoutes } from '@/router'
import RouterView from '@/router/routerView.js'
import Login from '@/views/login'

function authMap(asyncRoutes, authRouter){
    asyncRoutes.forEach((item, index) => {
        item.checked = authRouter[index].checked
        if(item.children){
            authMap(item.children, authRouter[index].children)
        }
    })
    return asyncRoutes
}

function filterAuthMap(data, parent = []){  //遍历整个数组，查找对应全选关系，parent存放所有节点信息
    data.forEach(item => {
        parent.push(item)
        let hasChildren = item.children !== undefined && Array.isArray(item.children) && item.children.length
        if(hasChildren){  //存在子节点，进行递归，把所有的子节点存入数组
            filterAuthMap(item.children, parent)
        }
        let arr = parent.reverse().filter(item => {  //parent倒叙遍历，即可从子节点往父节点进行遍历，过滤掉无子节点的项
            return item.children !== undefined
        })
        arr.forEach(item => {  //遍历倒叙后的节点，通过数组的引用关系，子节点修改数据后，同样该节点的父节点能拿到最新的子节点数据，直到顶层节点
            item.children = item.children.filter(_item => {  //遍历当前子节点，若所有子节点为选中状态，则当前节点为选中状态
                return _item.checked !== 2
            })
        })
    })
    data = data.filter(item => {
        return item.checked !== 2
    })
    return data
}

class FrontendAuth extends React.Component{
    shouldComponentUpdate(){
        const isLogin = store.getState().loginInfo.status
        if(isLogin && this.props.location.pathname !== '/login'){
            return false
        }
        return true
    }
    render(){
        const pathname = this.props.location.pathname
        const isLogin = store.getState().loginInfo.status
        if (isLogin) {  //登录验证判断
            if (pathname === "/login") {
                return <Redirect to="/" />
            } else {  //路由权限，根据用户role与路由表role匹配
                // let authRouter = store.getState().authRouter
                // let routesTable = authMap(asyncRoutes, authRouter)
                // routesTable = filterAuthMap(routesTable)
                // routesTable = [...routes, ...routesTable]
                let routesTable = [...routes, ...asyncRoutes]
                routesTable.push({
                    path: "*",
                    redirect: '/404',
                    hidden: true
                })
                routesTable = initRoutes(routesTable)
                return <RouterView currentRoutesTable={ routesTable } routesTable={ routesTable } {...this.props} />
            }
        } else {
            if(pathname === "/login"){
                return <Route path={ pathname } component={ Login }></Route>
            }else{
                return <Redirect to="/login" />
            }
        }
    }
}

FrontendAuth.propTypes = { 
	routesTable: PropTypes.array,
	location: PropTypes.object
}

export default FrontendAuth